package org.fengling.readingplatform.manager.service.impl;

import io.minio.*;
import org.fengling.readingplatform.common.exception.FenglingException;
import org.fengling.readingplatform.manager.properties.MinioProperties;
import org.fengling.readingplatform.manager.service.FileUploadService;
import org.fengling.readingplatform.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        try{
            // 创建MinioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                            .build();
            System.out.println(minioProperties.getBucketName());
            System.out.println(minioProperties.getEndpointUrl());
            System.out.println(minioProperties.getSecreKey());
            System.out.println(minioProperties.getAccessKey());
            // 创建bucket
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            System.out.println(found);
            if (!found) {
                System.out.println("我是sb");
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("bucket").build());
            } else {
                System.out.println("Bucket 'readingplatform-bucket' already exits.");
            }
            // 获取上传名称
            // 1 每个上传文件名称唯一
            // 2 根据当前内容对上传文件进行分组

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            String filename = uuid + file.getOriginalFilename();
            // 文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                            .object(filename)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());
            //获取上传文件在minio路径
            String url = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + filename;
            System.out.println("gg");
            System.out.println(url);
            return url;
        } catch (Exception e){
            e.printStackTrace();
            throw new FenglingException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }
}
